<template>
  <div class="vital-signs-monitor">
    <!-- 头部信息 -->
    <div class="monitor-header">
      <div class="header-left">
        <h3>{{ title }}</h3>
      </div>
      <div class="header-right">
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          添加
        </el-button>
      </div>
    </div>

    <!-- 监视数据图表 -->
    <div class="monitor-chart">
      <div ref="chartRef" style="width:100%;height:300px;min-height:300px;"></div>
    </div>
  </div>

  <!-- 参数设置弹窗 -->
  <el-dialog v-model="dialogVisible" title="参数设置" :width="dialogWidth" :close-on-click-modal="false">
    <div>
      <!-- 这里添加参数设置表单内容 -->
      <p>请设置相关参数...</p>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必须的组件
echarts.use([
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer
])
import { Plus, Right } from '@element-plus/icons-vue'
import { text } from 'stream/consumers'
import { width } from '@fortawesome/free-solid-svg-icons/fa0'

interface LegendItem {
  name: string
  show: boolean
  icon: string
  color: string
}

interface VitalSignsData {
  time: string[]
  heartRate: number[]
  respiration: number[]
  temperature: number[]
  bloodPressure: number[]
  bloodPressure2: number[]
  pulse: number[]
  map: number[]
}

interface Props {
  title?: string
  data24h?: VitalSignsData
  data48h?: VitalSignsData
  data72h?: VitalSignsData
  legend?: LegendItem[]
}

const props = withDefaults(defineProps<Props>(), {
  title: '生命体征',
  data24h: () => ({
    time: [],
    heartRate: [],
    respiration: [],
    temperature: [],
    bloodPressure: [],
    bloodPressure2: [],
    pulse: [],
    map: []
  }),
  data48h: () => ({
    time: [],
    heartRate: [],
    respiration: [],
    temperature: [],
    bloodPressure: [],
    bloodPressure2: [],
    pulse: [],
    map: []
  }),
  data72h: () => ({
    time: [],
    heartRate: [],
    respiration: [],
    temperature: [],
    bloodPressure: [],
    bloodPressure2: [],
    pulse: [],
    map: []
  }),
  legend: () => [
    {
      name: '心率',
      show: true,
      icon: 'path://M0,6 L18,6 M9,6 m-2,0 a2,2 0 1,0 4,0 a2,2 0 1,0 -4,0',
      color: '#000087'
    },
    {
      name: '呼吸',
      show: true,
      icon: 'path://M0,10 L20,10 M7,7 L13,13 M7,13 L13,7',
      color: '#ED7C30'
    },
    {
      name: '体温',
      show: true,
      icon: 'path://M0,6 L18,6 M9,6 m-2,0 a2,2 0 1,0 4,0 a2,2 0 1,0 -4,0',
      color: '#EE6666'
    },
    {
      name: '血压',
      show: true,
      icon: 'path://M0,6 L18,6 M9,6 m-2,0 a2,2 0 1,0 4,0 a2,2 0 1,0 -4,0',
      color: '#91CC75'
    },
    {
      name: '脉搏',
      show: true,
      icon: 'path://M0,6 L18,6 M9,6 m-2,0 a2,2 0 1,0 4,0 a2,2 0 1,0 -4,0',
      color: '#73C0DE'
    },
    {
      name: 'MAP',
      show: true,
      icon: 'path://M0,6 L18,6 M9,6 m-2,0 a2,2 0 1,0 4,0 a2,2 0 1,0 -4,0',
      color: '#9A60B4'
    }
  ]
})

const emit = defineEmits(['add'])

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null
const dialogVisible = ref(false)
const dialogWidth = ref('40%')

const handleAdd = () => {
  dialogVisible.value = true
}

const handleConfirm = () => {
  dialogVisible.value = false
  emit('add')
}

const handleCancel = () => {
  dialogVisible.value = false
}

const validateData = (data: any) => {
  if (!data || typeof data !== 'object') {
    console.error('数据不是对象', data)
    return false
  }

  const requiredKeys = ['time', 'heartRate', 'respiration', 'temperature']
  const isValid = requiredKeys.every(key => {
    if (!(key in data)) {
      console.error(`缺少必要字段: ${key}`)
      return false
    }
    if (!Array.isArray(data[key])) {
      console.error(`字段 ${key} 不是数组`, data[key])
      return false
    }
    return true
  })

  return isValid
}

const initChart = () => {
  if (!chartRef.value) {
    console.error('图表容器未找到')
    // 延迟重试
    setTimeout(initChart, 100)
    return
  }

  // 使用24小时数据作为默认显示
  const chartData = {
    time: Array.isArray(props.data24h?.time) ? props.data24h.time : [],
    heartRate: Array.isArray(props.data24h?.heartRate) ? props.data24h.heartRate :
      Array(72).fill(0).map((_, i) => 70 + Math.sin(i / 10) * 10),
    respiration: Array.isArray(props.data24h?.respiration) ? props.data24h.respiration :
      Array(72).fill(0).map((_, i) => 16 + Math.sin(i / 5) * 4),
    temperature: Array.isArray(props.data24h?.temperature) ? props.data24h.temperature :
      Array(72).fill(0).map((_, i) => 36.5 + Math.sin(i / 8) * 1.5),
    bloodPressure: Array.isArray(props.data24h?.bloodPressure) ? props.data24h.bloodPressure :
      Array(72).fill(120),
    bloodPressure2: Array.isArray(props.data24h?.bloodPressure2) ? props.data24h.bloodPressure2 :
      Array(72).fill(80),
    pulse: Array.isArray(props.data24h?.pulse) ? props.data24h.pulse :
      Array(72).fill(0).map((_, i) => 70 + Math.sin(i / 7) * 10),
    map: Array.isArray(props.data24h?.map) ? props.data24h.map :
      Array(72).fill(90)
  }

  if (!validateData(chartData)) {
    console.error('数据格式不正确，使用默认数据', props.data24h)
    return
  }

  try {
    chart = echarts.init(chartRef.value)
    console.log('图表初始化成功', chart)
  } catch (e) {
    console.error('图表初始化失败', e)
    return
  }

  const option = {
    color: ['#000087', '#ED7C30', '#EE6666', '#91CC75', '#73C0DE', '#9A60B4'], // 定义全局颜色数组
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      orient: 'vertical',
      left: '0',
      top: 'center',
      data: props.legend.filter(item => item.show).map(item => ({
        name: item.name,
        icon: item.icon,
        itemStyle: {
          color: item.color,
          borderColor: item.color,
          borderWidth: 2
        },
        itemWidth: 18,
        itemHeight: 18
      })),
      itemGap: 30,
      textStyle: {
        color: '#333',
        fontSize: 12
      },
    },
    // 配置图表容器边距
    grid: {
      left: '20%', // 为左侧多个Y轴留出更多空间
      right: '1%',
      top: '50px', // 固定顶部空间
      bottom: '1%',
      containLabel: false, // 禁用自动包含标签
      show: true,
      borderWidth: 0,
      backgroundColor: '#fff'
    },
    alignTicks: true,
    xAxis: {
      type: 'category',
      boundaryGap: false,
      position: 'top', // 将x轴移到图表上方
      offset: 0, // 重置偏移量
      data: chartData.time,
      axisLabel: {
        align: 'center',
        interval: 1,
        verticalAlign: 'top',
        margin: 14, // 增加标签与轴线的间距
        formatter: (value: string, index: number) => {
          if (!value) return '';
          const date = new Date(value);
          if (date.getHours() === 12 || date.getHours() === 0 || date.getHours() === 23) {
            if (date.getHours() === 12) {
              return date.toISOString().slice(0, 10); // YYYY-MM-DD format
            } else {
              return '|';
            }
          } else {
            return '';
          }
        },
      },
      axisTick: {
        alignWithLabel: true,
        length: 5, // 增加刻度线长度
        lineStyle: {
          color: '#333',
          width: 1
        },
        inside: true // 强制刻度线显示在图表内部
      },
      axisLine: {
        lineStyle: {
          color: '#333',
          width: 1
        },
        onZero: false // 禁用与零刻度对齐
      },
      z: 10, // 设置更高的z-index
      splitLine: {
        show: true,
        lineStyle: {
          color: '#999',
          opacity: 0.7,
          type: 'dashed',
          width: 1,
          dashOffset: 3
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '呼吸',
        position: 'left',
        offset: 110,
        min: 0,
        max: 200,
        interval: 10,
        axisLine: {
          lineStyle: {
            color: '#ED7C30'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#999',
            opacity: 0.7,
            type: 'dashed',
            width: 1.5,
            dashOffset: 3
          }
        },

        axisLabel: {
          formatter: (value: any) => {
            if (value < 0 || value > 60) return ''; // 隐藏超出0~100的标签
            return value;
          },
          align: 'center'
        },
        nameTextStyle: {
          align: 'right'
        }
      },
      {
        type: 'value',
        name: '体温',
        position: 'left',
        offset: 80,
        min: 0,
        max: 200,
        interval: 10,
        axisLine: {
          lineStyle: {
            color: '#EE6666'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#999',
            opacity: 0.7,
            type: 'dashed',
            width: 1.5,
            dashOffset: 5
          }
        },
        axisLabel: {
          formatter: (value: any) => {
            if (value < 34 || value > 40) return ''; // 隐藏超出0~100的标签
            return value;
          },
          align: 'center'
        },
        nameTextStyle: {
          align: 'right'
        }
      },
      {
        type: 'value',
        name: '心率',
        position: 'left',
        offset: 50,
        min: 0,
        max: 200,
        interval: 10,
        axisLine: {
          lineStyle: {
            color: '#000087'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#999',
            opacity: 0.7,
            type: 'dashed',
            width: 1,
            dashOffset: 3
          }
        },
        axisLabel: {
          formatter: (value: any) => {
            if (value < 100 || value > 180) return ''; // 隐藏超出0~100的标签
            return value;
          },
          align: 'center'
        },
        nameTextStyle: {
          align: 'right',
        }
      },


      {
        type: 'value',
        name: '血压',
        position: 'left',
        offset: 20,
        min: 0,
        max: 200,
        interval: 10,
        axisLine: {
          lineStyle: {
            color: '#91CC75'
          }
        },

        axisLabel: {
          formatter: (value: any) => {
            if (value < 70 || value > 190) return ''; // 隐藏超出0~100的标签
            return value;
          },
          align: 'center'
        },
        nameTextStyle: {
          align: 'right',
        }
      },

    ],
    series: [
      {
        name: '心率',
        type: 'line',
        data: chartData.heartRate,
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        lineStyle: {
          width: 1
        },
        itemStyle: {
          color: '#ff4d4f'
        }
      },
      {
        name: '呼吸',
        type: 'line',
        showSymbol: true,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: '#ED7C30'
        },
        lineStyle: {
          color: '#ED7C30',
          width: 1
        },
        data: chartData.respiration
      },
      {
        name: '体温',
        type: 'line',
        showSymbol: true,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: '#EE6666'
        },
        lineStyle: {
          color: '#EE6666',
          width: 1
        },
        data: chartData.temperature
      },
      {
        name: '血压',
        type: 'line',
        showSymbol: true,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: '#91CC75'
        },
        lineStyle: {
          color: '#91CC75',
          width: 1
        },
        data: chartData.bloodPressure.length > 0 ? chartData.bloodPressure : [0, 0, 0, 0, 0]
      },
      {
        name: '脉搏',
        type: 'line',
        showSymbol: true,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: '#73C0DE'
        },
        lineStyle: {
          color: '#73C0DE',
          width: 1
        },
        data: chartData.pulse.length > 0 ? chartData.pulse : [0, 0, 0, 0, 0]
      },
      {
        name: 'MAP',
        type: 'line',
        showSymbol: true,
        symbol: 'circle',
        symbolSize: 4,
        itemStyle: {
          color: '#9A60B4'
        },
        lineStyle: {
          color: '#9A60B4',
          width: 1
        },
        data: chartData.map.length > 0 ? chartData.map : [0, 0, 0, 0, 0]
      }
    ]
  }

  chart.setOption(option)
}

onMounted(() => {
  initChart()
})

watch(() => props.data, () => {
  if (chart) {
    initChart()
  }
}, { deep: true })
</script>

<style scoped>
.vital-signs-monitor {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background: #fff;
}

.monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0px;
  background: var(--bar-bg);
  border: 1px solid var(--border-color);
  border-radius: 2px;
  padding: 4px;
}


.header-left h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.monitor-chart {
  border: 1px solid var(--border-color);
  border-radius: 2px;
  height: 300px;
}
</style>
